package com.redispro.service.impl;

import cn.hutool.core.util.*;
import cn.hutool.json.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.redispro.dto.Result;
import com.redispro.entity.Shop;
import com.redispro.mapper.ShopMapper;
import com.redispro.service.IShopService;
import com.redispro.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 李力
 * @since 2022-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //缓存穿透+雪崩
//    @Override
//    public Result queryShopDetail(Long id) {
//        if (id == null) {
//            return Result.fail("id为null");
//        }
//        //1.从redis查询信息
//        String shopInfo = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
//        //2.判断是否存在
//        if (StrUtil.isNotBlank(shopInfo)) {
//            Shop shop = JSONUtil.toBean(shopInfo, Shop.class);
//            return Result.ok(shop);
//        }
//        //判断是否命中的空值,不=null，说明为空串
//        if (shopInfo != null) {
//            return Result.fail("店铺信息不存在");
//        }
//        //3.不存在
//        Shop shop = getById(id);
//        //4.往redis中存入数据
//        if (shop != null) {
//            //4.1数据库查询不为空
//            //给不同的key设置一个随机的ttl，防止缓存雪崩
//            int ttl = RandomUtil.randomInt(10, 30);
//            redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), ttl, TimeUnit.MINUTES);
//            //5.返回数据
//            return Result.ok(shop);
//        } else {
//            //4.2数据库查询为空,添加空字符串，防止缓存穿透
//            redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", 3, TimeUnit.MINUTES);
//            //5.返回数据
//            return Result.fail("店铺信息不存在");
//        }
//    }


    //缓存击穿-互斥锁方案
    @Override
    public Result queryShopDetail(Long id) {
        if (id == null) {
            return Result.fail("id为null");
        }
        //1.从redis查询信息
        String shopInfo = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //2.判断是否存在
        if (StrUtil.isNotBlank(shopInfo)) {
            Shop shop = JSONUtil.toBean(shopInfo, Shop.class);
            return Result.ok(shop);
        }
        //判断是否命中的空值,不=null，说明为空串
        if (shopInfo != null) {
            return Result.fail("店铺信息不存在");
        }
        try {
            //3.不存在,实现缓存重建
            boolean b = tryLock(RedisConstants.LOCK_SHOP_KEY + id);
            //3.1获取互斥锁失败
            if (!b) {
                //休眠
                Thread.sleep(50);
                //重试
                return queryShopDetail(id);
            }
            //3.2获取互斥锁成功
            Shop shop = getById(id);
            //4.往redis中存入数据
            if (shop != null) {
                //4.1数据库查询不为空
                //给不同的key设置一个随机的ttl，防止缓存雪崩
                int ttl = RandomUtil.randomInt(10, 30);
                redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), ttl, TimeUnit.MINUTES);
                //5.返回数据
                return Result.ok(shop);
            } else {
                //4.2数据库查询为空,添加空字符串，防止缓存穿透
                redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", 3, TimeUnit.MINUTES);
                //5.返回数据
                return Result.fail("店铺信息不存在");
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            unLock(RedisConstants.LOCK_SHOP_KEY + id);
        }
        return null;
    }


    //缓存击穿-逻辑过期
//    @Override
//    public Result queryShopDetail(Long id) {
//        if (id == null) {
//            return Result.fail("id为null");
//        }
//        //1.从redis查询信息
//        String shopInfo = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
//        //2.判断是否存在
//        //不存在：当然热点key我们会提前会把数据存入缓存中，默认命中
//        if (StrUtil.isBlank(shopInfo)) {
//            return Result.ok(null);
//        }
//        //存在
//        //4.判断是否逻辑过期
//        RedisData redisData = JSONUtil.toBean(shopInfo, RedisData.class);
//        JSONObject data = (JSONObject) redisData.getData();
//        Shop shop = JSONUtil.toBean(data, Shop.class);
//        LocalDateTime expireTime = redisData.getExpireTime();
//        if (expireTime.isAfter(LocalDateTime.now())) {
//            //4.1没过期,直接返回信息
//            return Result.ok(shop);
//        }
//        //4.2过期
//        try {
//            //5.获取互斥锁
//            boolean result = tryLock(RedisConstants.LOCK_SHOP_KEY + id);
//            if (result) {
//                //5.1获取锁成功
//                ExecutorService executorService = Executors.newCachedThreadPool();
//                executorService.submit(() -> {
//                    saveShopToRedis(id, 30L);
//                });
//            }
//            //6.返回店铺信息
//            return Result.ok(shop);
//        } catch (Exception exception) {
//            exception.printStackTrace();
//        } finally {
//            unLock(RedisConstants.LOCK_SHOP_KEY + id);
//        }
//        return null;
//    }

    private void saveShopToRedis(Long id, Long time) {
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusMinutes(time));
        redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }


    //尝试获取锁: 注意并不是真正的redis锁的实现方案
    private boolean tryLock(String key) {
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, RedisConstants.LOCK_SHOP_VALUE, 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    //释放锁
    private void unLock(String key) {
        redisTemplate.delete(key);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateShop(Shop shop) {
        if (ObjectUtil.isNull(shop)) {
            return Result.fail("参数为null");
        }
        //1.更新数据库
        boolean result = updateById(shop);
        if (!result) {
            throw new RuntimeException("更新失败");
        }
        //2.删除缓存
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("id为null");
        }
        redisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        if (typeId == null) {
            return Result.fail("参数为null");
        }
        //1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            //不需要坐标查询，按照数据库查询
            Page<Shop> page = query().eq("type_id", typeId).
                    page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        //2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //3.查询redis,分页
        String key = "shop:geo:" + typeId;
        /*
         * 参数1: key
         * 参数2: 圆心
         * 参数3: 半径值，单位默认米，结果也是米
         * 参数4: 查询参数
         * */
        GeoResults<RedisGeoCommands.GeoLocation<String>> search = redisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(1000),
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(end)
        );
        //4.解析结果
        if (search == null) {
            return Result.ok(null);
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = search.getContent();
        if (content.size() <= from) {
            return Result.ok(null);
        }
        //5.截取from-end的部分
        List<Long> ids = new ArrayList<>(content.size());
        Map<String, Distance> map = new HashMap<>();
        content.stream().skip(from).forEach(r -> {
            //获取店铺id
            RedisGeoCommands.GeoLocation<String> location = r.getContent();
            String shopId = location.getName();
            ids.add(Long.valueOf(shopId));
            //获取距离
            Distance distance = r.getDistance();
            map.put(shopId, distance);
        });
        //6.根据id批量查询
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("ids", ids).last("order by field(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(map.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }
}
